﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net;
using System.Web;
using System.IO;
using System.Diagnostics;
using DahuaMes;
using Newtonsoft.Json.Linq;
using System.Drawing;

namespace DaHuaMes
{
    public class KDDMes_Data
    {

        public string user { get; set; }//用户
        public string password { get; set; }//密码

        public string process { get; set; }//工序

        public string Sn { get; set; }//镭雕码
        public string imageUrl { get; set; } = "";//图片网址

        public string logUrl { get; set; } = "";//登录网址

        public string upUrl { get; set; } = "";//上传网址

    }
    public class MesFun
    {
        private static MesFun instance;
        private static readonly object _lock = new object();
        public static string bigPictureToken = "";//全局Token
        public static string startTime = "";
        public static bool b_isLog = false;
    
        public KDDMes_Data Mes_Data = new KDDMes_Data();
        public static MesFun Instance
        {
            get
            {
                lock (_lock)
                {
                    if (instance == null)
                    {
                        instance = new MesFun();
                    }
                }
                return instance;
            }
        }

        public void Load()
        {
            //对数据进行初始化
            string currentFile = AppDomain.CurrentDomain.BaseDirectory + @"\MesInfo.json";
            if (!File.Exists(currentFile))
            {
                Sava_MesData();
            }
            var sr = new StreamReader(currentFile);
            Mes_Data = JsonConvert.DeserializeObject<KDDMes_Data>(sr.ReadToEnd());
            sr.Dispose();
            return;
        }
        public void Sava_MesData()
        {
            string currentFile = AppDomain.CurrentDomain.BaseDirectory + @"\MesInfo.json";
            string json = JsonConvert.SerializeObject(Mes_Data);
            FileStream fs = new FileStream(currentFile, FileMode.Create, FileAccess.Write);
            if (fs != null)
            {
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                sw.WriteLine(json);
                sw.Close();
            }
            fs.Close();
            return;
        }


        public bool Login(UserLoginClass userLogin, ref string token,ref string msg)
        {
            string Url = Mes_Data.logUrl;
            string str = JsonConvert.SerializeObject(userLogin);

            string json;
            try
            {
                json = HttpWebRequest_Pro(Url, 10, str, "UTF-8", out msg, "");
            }
            catch (Exception ex)
            {
                msg = "NG" + $"连接异常,原因{ex}";
                return false;
            }
            if (msg == "OK" && json != "" && json != null)
            {

                    string s = json;
                    TokenClass tokenClass = JsonConvert.DeserializeObject<TokenClass>(json);
                    msg =msg+ json;
                if (tokenClass.resultData==null)
                {
                    return false;
                }
                    token = tokenClass.resultData.accessToken;
                     bigPictureToken = token;
                 
                    return true;

            }
            msg = "NG" + msg;
            return false;
        }

        public bool checkSn(WebSnClass snClass, string token,ref string msg)
        {
           

            snClass.docType = "DAHUA_ZERO_MES_MO_LB";
            string str = JsonConvert.SerializeObject(snClass);

            startTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            string Url = Mes_Data.upUrl;

            string json = "";
            string endCode = "";
            try
            {
              Logger.Log.Add("Mes", $"Mes入站上传：{str}");
                json = HttpWebRequest_Pro(Url, 10, str, "UTF-8", out msg, token);
                Logger.Log.Add("Mes", $"Mes入站接收：{json}", Logger.LogType.Warning);

                ResponseClass responseClass = JsonConvert.DeserializeObject<ResponseClass>(json);

                endCode = responseClass.resultCode;
            }
            catch (Exception ex)
            {
                msg = "NG" + $"连接异常,原因{ex}";
                return false;
            }
            if (msg == "OK")
            {
                if (endCode == "0000")
                {
                    msg = msg + json;
                    return true;
                }
            }
            msg = "NG" +json;
            return false;
          
        }

        public bool exitStation(WebSnClass exClassone, string token, ref string msg)
        {
            WebSnClass exClass = new WebSnClass();
            funAddCondtion(ref exClass,exClassone);
            exClass.docType = "DAHUA_AA_SELECT";          
            string str = JsonConvert.SerializeObject(exClass);   
            string endCode = "";
            string Url = Mes_Data.upUrl;
            string json = "";
            try
            {
                Logger.Log.Add("Mes", $"Mes出站上传：{str}");
                json = HttpWebRequest_Pro(Url, 10, str, "UTF-8", out msg, token);
                Logger.Log.Add("Mes", $"Mes出站接收：{json}", Logger.LogType.Warning);

                ResponseClass responseClass = JsonConvert.DeserializeObject<ResponseClass>(json);
                endCode = responseClass.resultCode;
            }
            catch (Exception ex)
            {
                msg = $"连接异常,原因{ex}";
                return false;
            }
            if (msg == "OK")
            {
                if (endCode == "0000")
                {
                    msg = msg + json;
                    return true;
                }
            }
            msg = "NG" + json;
            return false;
        }
        public void funAddCondtion(ref WebSnClass exClass, WebSnClass exClassone)
        {

            Condition condition = new Condition();
            condition.columnName = "SN";
            condition.value = exClassone.condition[0].value;
            exClass.condition.Add(condition);
            condition = new Condition();
            condition.columnName = "WP_CODE";
            condition.value = exClassone.condition[1].value;
            exClass.condition.Add(condition);
            condition = new Condition();

            condition.columnName = "MO_CODE";
            condition.value = "";
            exClass.condition.Add(condition);



            condition = new Condition();
            condition.columnName = "MTRL_CODE";
            condition.value = "";
            exClass.condition.Add(condition);

            condition = new Condition();
            condition.columnName = "DEV_CODE";
            condition.value = "test-dev";
            exClass.condition.Add(condition);


            condition = new Condition();
            condition.columnName = "PROGRAM_NAME";
            condition.value = "test-pn";
            exClass.condition.Add(condition);

            condition = new Condition();
            condition.columnName = "software_version";
            condition.value = "test-sv";
            exClass.condition.Add(condition);

            condition = new Condition();
            condition.columnName = "OR_CODE";
            condition.value = "test-or";
            exClass.condition.Add(condition);

            condition = new Condition();
            condition.columnName = "AA_START_TIME";
            condition.value = startTime;
            exClass.condition.Add(condition);

            condition = new Condition();
            condition.columnName = "AA_STOP_TIME";
            condition.value = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            exClass.condition.Add(condition);

            condition = new Condition();
            condition.columnName = "AA_TEST_RESULT";
            condition.value = exClassone.condition[2].value;
            exClass.condition.Add(condition);

            condition = new Condition();
            condition.columnName = "JUDGE_CODE";
            condition.value = "0";
            exClass.condition.Add(condition);

            condition = new Condition();
            condition.columnName = "ORIGINAL_PICTURE";
            condition.value = "";
            exClass.condition.Add(condition);


            condition = new Condition();
            condition.columnName = "TEST_PICTURE";
            condition.value = "";
            exClass.condition.Add(condition);


            condition = new Condition();
            condition.columnName = "VICE_VALUE";
            string str = JsonConvert.SerializeObject(exClassone.condition[3].value);
            condition.value =str;
            exClass.condition.Add(condition);
        }
        public bool getTicket(WebSnClass exClass, string token, ref string msg)
        {
            exClass.docType = "DAHUA_MES_MO_SN";
            string str = JsonConvert.SerializeObject(exClass);
             string endCode = "";
            string Url = Mes_Data.upUrl;
            string json = "";
            try
            {
                json = HttpWebRequest_Pro(Url, 100, str, "UTF-8", out msg, token);

                ResponseClass responseClass = JsonConvert.DeserializeObject<ResponseClass>(json);
                endCode = responseClass.resultCode;
            }
            catch (Exception ex)
            {
                msg = $"连接异常,原因{ex}";
                return false;
            }
            if (msg == "OK")
            {
                if (endCode == "0000")
                {
                    msg = msg + json;
                    return true;
                }
            }
            msg = "NG" + json;
            return false;
        }

        public bool PCBADing(WebSnClass exClass, string token, ref string msg)
        {
            exClass.docType = "DAHUA_PCBA_SN";
            string str = JsonConvert.SerializeObject(exClass);
            string endCode = "";
            string Url = Mes_Data.upUrl;
            string json = "";
            try
            {
                json = HttpWebRequest_Pro(Url, 100, str, "UTF-8", out msg, token);

                ResponseClass responseClass = JsonConvert.DeserializeObject<ResponseClass>(json);
                endCode = responseClass.resultCode;
            }
            catch (Exception ex)
            {
                msg = $"连接异常,原因{ex}";
                return false;
            }
            if (msg == "OK")
            {
                if (endCode == "0000")
                {
                    msg = msg + json;
                    return true;
                }
            }
            msg = "NG" + json;
            return false;
        }
        //path：图片上传路径  如："C:/Users/Administrator/Desktop/image.bmp"
        //sn
        public bool Fun_图片上传(PicturesClass picturesClass,ref string msg)
        {
            string str = JsonConvert.SerializeObject(picturesClass);
            string endCode = "";
            string Url = Mes_Data.imageUrl;
            string json = "";
            try
            {
                json = HttpWebRequest_Pro(Url, 100, str, "UTF-8", out msg, "");

                /*ResponseClass responseClass = JsonConvert.DeserializeObject<ResponseClass>(json);
                endCode = responseClass.resultCode;*/
            }
            catch (Exception ex)
            {
                msg = $"连接异常,原因{ex}";
                return false;
            }

                if (json.Contains("200"))
                {
                    msg = msg + json;
                    return true;
                }

            msg = "NG" + json;
            return false;
        }
   
        public static string HttpWebRequest_Pro(string requestUrl, int timeout, string requestContent, string encoding, out string msg, string token)
        {

            msg = "OK";
            string result = string.Empty;
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(requestContent);//System.Text.Encoding.GetEncoding(encoding).GetBytes($"{requestContent}");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
                request.ContentType = "application/json";
                request.Referer = requestUrl;
                request.Method = "Post";
                if (!requestUrl.Contains("login") && token == "")
                {
                    request.Headers.Add("accessToken", bigPictureToken);
                }
                else
                {
                    request.Headers.Add("accessToken", token);
                }

                request.ConnectionGroupName = requestContent;
                request.Timeout = timeout * 1000;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                if (responseStream != null)
                {
                    StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(encoding));
                    result = reader.ReadToEnd();
                    reader.Close();
                    responseStream.Close();
                    request.Abort();
                    response.Close();
                    return result.Trim();
                }
            }
            catch (Exception ex)
            {
                msg = "exception" + ex.Message + ex.StackTrace;
                result = ex.Message + ex.StackTrace;
            }
            return result;
        }


        /// <summary>
        /// base64 转 Image
        /// </summary>
        /// <param name="base64"></param>
        public static void Base64ToImage(string base64)
        {
            base64 = base64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
            byte[] bytes = Convert.FromBase64String(base64);
            MemoryStream memStream = new MemoryStream(bytes);
            Image mImage = Image.FromStream(memStream);
            Bitmap bp = new Bitmap(mImage);
            bp.Save("C:/Users/Administrator/Desktop/" + DateTime.Now.ToString("yyyyMMddHHss") + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);//注意保存路径
        }

        /// <summary>
        /// Image 转成 base64
        /// </summary>
        /// <param name="fileFullName"></param>
        public static string ImageToBase64(string fileFullName)
        {
            try
            {
                Bitmap bmp = new Bitmap(fileFullName);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length]; ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length); ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
